<template>
  <BasicModal v-bind="$attrs" @register="registerModal" destroyOnClose :title="title" :width="900" @ok="handleSubmit" :okText="'保存'">
      <BasicForm @register="registerForm" @eventFormModel="eventFormModel">
        <template #type="{model, field}">
            <JDictSelectTag :value="placeholder" :placeholder="placeholder" :state="2" dictCode="projectType" @change="changeType"/>
        </template>

      </BasicForm>
      <a-alert message=" " type="warning">
            <template #description>
            <div>
            <!-- 显示项目 合同额 - 运营占比 - 利润率剩余的金额 -->
              当前剩余: {{ nowQuota }}
            </div>
            <!-- <p>当人力成本输入的时候 这个值会减掉一部分</p>
            <p>当差旅输入 到时候。这个值减掉差旅成本 </p>
            <p>当地方输入的时候减掉第三方成本</p>
            <p>当其他成本输入的时候减掉其他成本</p> -->
            </template>
        </a-alert>
      <VerifyInfo ref="childRef" :verifyType="1"/>
  </BasicModal>
</template>

<script lang="ts" setup>
    import {ref, computed, unref} from 'vue';
    import dayjs from 'dayjs'
    import {BasicModal, useModalInner} from '/@/components/Modal';
    import { JDictSelectTag } from '/@/components/Form'
    import { useMessage } from '/@/hooks/web/useMessage';
    import VerifyInfo from './verifyInfo.vue'
    import {BasicForm, useForm} from '/@/components/Form/index';
    import {formSchema} from '../MonsterRocProjectSetup.data';
    import {saveOrUpdate,getRcConfig} from '../MonsterRocProjectSetup.api';
    import { USER_INFO_KEY } from '/@/enums/cacheEnum'
    import { getAuthCache } from '/@/utils/auth'
    let user:any = getAuthCache(USER_INFO_KEY) || {}
    const childRef = ref()
    const nowQuota:any = ref(0)
    const configs:any = ref({})
    const placeholder = ref('请选择')
    const type = ref('')
    // Emits声明
    const emit = defineEmits(['register','success','advanced-change']);
    const isUpdate = ref(true);
    //表单配置 updateSchema
    const [registerForm, {setProps,resetFields, setFieldsValue, validate, updateSchema}] = useForm({
        labelWidth: 120,
        schemas: formSchema,
        showActionButtonGroup: false,
        baseColProps: {span: 12}
    });
    // 立项通过可编辑项 contractStatus  projectStatus  endTime
    //表单赋值
    const [registerModal, {setModalProps, closeModal}] = useModalInner(async (data) => {
        //重置表单
        await resetFields();
        setModalProps({confirmLoading: false,showCancelBtn:!!data?.showFooter,showOkBtn:!!data?.showFooter});
        isUpdate.value = !!data?.isUpdate;
        nowQuota.value = 0
        placeholder.value = '请选择'
        // if (unref(isUpdate)) {
        if (data.record) {
            placeholder.value = data.record.type ? data.record.type.toString() : '请选择'
            type.value = data.record.type
            if(data.record.setupStatus == 3) {
                formSchema.forEach((item:any) => {
                    if(item.field != 'contractStatus' && item.field != 'projectStatus' && item.field != 'endTime' && item.field != 'createBy' && item.field != 'totalCost' && item.field != 'cycle' && item.field !='contractAmountWithoutFax' && item.field !='operationAmount' && item.field !='kpiAmount' && item.field !='faxAmount') {
                        updateSchema({ field: item.field, componentProps: { disabled: true }})
                    }
                })
            }else{
                formSchema.forEach((item:any) => {
                    if(item.field != 'operationPercent' && item.field != 'kpi'&& item.field != 'faxPercent' && item.field != 'setupStatus' && item.field != 'createBy' && item.field != 'totalCost' && item.field != 'cycle' && item.field !='contractAmountWithoutFax' && item.field !='operationAmount' && item.field !='kpiAmount' && item.field !='faxAmount') {
                        updateSchema({ field: item.field, componentProps: { disabled: false }})
                    }
                })
            }
            //表单赋值
            await setFieldsValue({
                ...data.record,
            });
        }
        if(unref(isUpdate)) {
            childRef.value.childMethod(data.record)
        }else {
            childRef.value.childMethod()
        }
        // 隐藏底部时禁用整个表单
       setProps({ disabled: !data?.showFooter })
    });
    //设置标题
    const title = computed(() => (!unref(isUpdate) ? '新增' : '编辑'));
    //表单提交事件
    async function handleSubmit(v) {
        try {
            const { createMessage } = useMessage()
            let values = await validate();

            if(!type.value) {
                return createMessage.warn('请选择项目类型');
            }
            let f = values.uploadFile ? JSON.parse(values.uploadFile) : []
            let file:any = []
            f.forEach((url) => {
                file.push({
                    annexName: url.fileName,
                    annexType: url.fileType,
                    url: url.filePath,
                })
            })
            if(nowQuota.value && nowQuota.value < 0) {
                return createMessage.warn('已超出限额，无法提交');
            }
            console.log('file', file, values)
            values.uploadFile = JSON.stringify(file)
            setModalProps({confirmLoading: true});
            //提交表单
            await saveOrUpdate(Object.assign(values,{annex:JSON.stringify(file),pm:user.id,projectStatus:0, type: type.value}), isUpdate.value);
            //关闭弹窗
            closeModal();
            //刷新列表
            emit('success');
        } finally {
            setModalProps({confirmLoading: false});
        }
    }
    let oTime

    function c () {
        getRcConfig().then((res) => {
            configs.value = res
        })
    }
    c()
    let kpi = 0
    function changeType (e) {
        if(e == 1) {
            kpi = configs.value.rkpi
        }
        if(e == 2) {
            kpi = configs.value.ckpi
        }
        if(e == 3) {
            kpi = configs.value.okpi
        }
        type.value = e
        setFieldsValue({
            kpi: kpi
        })
    }
    // 这个是用不含税的金额 - 不含税的金额*运营占比 = 结果a
    // 结果a - 结果a*kpi  = 剩余可用
    function eventFormModel (e) {
        let totalNum = Number(e.laborCost ? e.laborCost : 0) + Number(e.tripCost ? e.tripCost : 0) + Number(e.supplierCost ? e.supplierCost : 0) + Number(e.otherCost ? e.otherCost : 0)//Number(a) + Number(b) + Number(c)
        if(totalNum) {
            setFieldsValue({ totalCost: totalNum })
        }
        if(e.contractAmount) {
            //let cf = Number(e.contractAmount) - Number(Number(e.contractAmount) * Number(e.faxPercent))
            let cf = (Number(Number(e.contractAmount) / (Number(e.faxPercent)+Number(1)))).toFixed(2)
            setFieldsValue({
                contractAmountWithoutFax: cf,
                // kpi: kpi,
                operationAmount: (Number(cf) * Number(e.operationPercent)).toFixed(2),
                kpiAmount: (Number(cf) * Number(e.kpi)).toFixed(2),
                faxAmount: (Number(e.contractAmount) - Number(cf)).toFixed(2),
            })
            // 用合同额  - 合同额* 0.06 就可以  0.06 是死的
            const { createMessage } = useMessage()
            //剩余额度 = 合同额 -（合同额*KPI - 合同额* 运营占比  - 合同额*税点）
            // let s = Number(e.contractAmount) - (e.contractAmount * e.kpi + e.contractAmount * e.operationPercent + e.contractAmount * e.faxPercent)
            // nowQuota.value = s -  Number(e.laborCost?e.laborCost:0) - Number(e.tripCost?e.tripCost:0) - Number(e.supplierCost?e.supplierCost:0) - Number(e.otherCost?e.otherCost:0)
            // 合同额 - 运营占比 - 利润率剩余的金额
            // let remans = Number(s?s:0) - Number(e.laborCost?e.laborCost:0) - Number(e.tripCost?e.tripCost:0) - Number(e.supplierCost?e.supplierCost:0) - Number(e.otherCost?e.otherCost:0)

            // 用不含税的金额 - 不含税的金额*运营占比 = 结果a
            // 结果a - 结果a*kpi  = 剩余可用
            let n = Number(cf) - Number(e.operationAmount) - Number(e.kpiAmount)
           // nowQuota.value = (Number(n) - Number(n) * kpi).toFixed(2)

            nowQuota.value = (Number(n) - Number(e.laborCost?e.laborCost:0) - Number(e.tripCost?e.tripCost:0) - Number(e.supplierCost?e.supplierCost:0) - Number(e.otherCost?e.otherCost:0)).toFixed(2)

            // let remans = Number(n?n:0) - Number(e.laborCost?e.laborCost:0) - Number(e.tripCost?e.tripCost:0) - Number(e.supplierCost?e.supplierCost:0) - Number(e.otherCost?e.otherCost:0)

            if(nowQuota.value && nowQuota.value < 0) {
                return createMessage.warn('已超出限额，无法提交');
            }
        }

/*        if(e.faxPercent ) {
          let contractAmountWithoutFax1 = Number(e.contractAmount) - Number(Number(e.contractAmount) * Number(e.faxPercent))
          console.log(contractAmountWithoutFax1);
          setFieldsValue({
            contractAmountWithoutFax: contractAmountWithoutFax1,
            faxAmount: (Number(e.contractAmount) * Number(e.faxPercent)).toFixed(2),
          })
        }*/

        let cycle = dayjs(e.endTime).diff(e.startTime, 'day')

        if(cycle && e.endTime) {
            setFieldsValue({ cycle })
        }

        if(oTime != e.startTime) {
            // setFieldsValue({ endTime: '' })
        }

        if(e && e.startTime) {
            oTime = e.startTime
            updateSchema({ field: 'endTime', componentProps: { disabledDate: disabledDate }})
        }

        function disabledDate(current) {
            return current && current < dayjs(e.startTime).subtract(0, 'days').endOf('day')//currentTime < endTime;//禁用小于开始时间的日期
        }
    }

/*        handleInputChange(e) {
          console.log('Input changed:', e.target.value);
          // 在这里处理input内容变化后的逻辑
    }*/

</script>

<style lang="less" scoped>
	/** 时间和数字输入框样式 */
  :deep(.ant-input-number){
		width: 100%
	}

	:deep(.ant-calendar-picker){
		width: 100%
	}
</style>
